package com.dflc.controller.BackManageController;

import cn.dev33.satoken.session.TokenSign;
import cn.dev33.satoken.stp.StpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.dflc.annotations.CheckUser;
import com.dflc.common.CommonConstant;
import com.dflc.entity.po.SysMenu;
import com.dflc.entity.po.SysRole;
import com.dflc.entity.po.SysUserRole;
import com.dflc.entity.po.TBackLoginUser;
import com.dflc.entity.rep.HttpResponseEntity;
import com.dflc.entity.req.QueryUserReq;
import com.dflc.entity.req.TBackLoginUserReq;
import com.dflc.entity.req.UserPasswordReq;
import com.dflc.entity.vo.*;
import com.dflc.mapper.SysRoleMapper;
import com.dflc.mapper.SysUserRoleMapper;
import com.dflc.mapper.TBackLoginUserMapper;
import com.dflc.service.SysMenuService;
import com.dflc.service.SysUserRoleService;
import com.dflc.service.TBackLoginUserService;
import com.dflc.utils.*;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationEventPublisher;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.ObjectUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.validation.Valid;
import java.util.*;
import java.util.stream.Collectors;

/**
 * 后台账号信息操作
 *
 * @author tqx
 * @version 1.0.0.0
 * <p>Title: SysUserInfoController </p >
 * <p>Description: 后台账号信息操作  </p >
 * Package: com.dflc.controller
 * Copyright: Copyright(c) 产品研发与安全部
 * Date: 2024年11月27日 15:50
 */
@RestController
@Slf4j
@RequestMapping("/backUserInfo")
public class SysUserInfoController {

    @Resource
    private TBackLoginUserService tBackLoginUserService;
    @Resource
    private TBackLoginUserMapper tBackLoginUserMapper;
    @Resource
    private SysUserRoleMapper sysUserRoleMapper;
    @Resource
    private SysUserRoleService sysUserRoleService;
    @Resource
    private SysMenuService sysMenuService;
    @Resource
    public SysRoleMapper sysRoleMapper;
    @Resource
    private ApplicationEventPublisher eventPublisher;

    @Value("${sm4.secretKey}")
    private String secretKey;

    @Value("${sm4.firstPw}")
    private String firstPw;

    @Value("${sa-token.is-concurrent}")
    private Boolean isConcurrent;

    /**
     * 获取当前账号用户信息
     *
     * @return HttpResponseEntity<LoginUserInfo>
     * @author tqx
     * @date 2023/6/6 11:30
     * Description: 获取当前账号用户信息
     */
    @GetMapping("/getUserInfo")
    public HttpResponseEntity getUserInfo() {
        Integer id = StpUtil.getLoginIdAsInt();
        try {
            TBackLoginUser sysLoginUser = tBackLoginUserService.getById(id);
            if (sysLoginUser == null) {
                return HttpResponseEntity.error(500, "查询不到当前用户的信息！请检查数据！");
            }else if (sysLoginUser.getState().intValue()==CommonConstant.StateActive.Deleted.intValue()) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
            LoginUserInfoVo vo = new LoginUserInfoVo();
            vo.setName(sysLoginUser.getName());
            vo.setUserName(sysLoginUser.getUserName());
            vo.setPhone(sysLoginUser.getPhone());
            vo.setDepartmentId(sysLoginUser.getDepartmentId());
            vo.setUnitId(sysLoginUser.getUnitId());
            //查询单位名称和部门（科室名称）
            Map<String, Object> params5 = new HashMap<>();
            params5.put("id", id);
            params5.put("state",CommonConstant.StateActive.Active);
            List<TBackLoginUserVo> list2 = tBackLoginUserMapper.findAllByMap2(params5);
            vo.setDepartmentName(list2.get(0).getDepartmentName());
            vo.setUnitName(list2.get(0).getUnitName());
            //end
            vo.setIsAdmin(sysLoginUser.getIsAdmin());
            vo.setId(Math.toIntExact(sysLoginUser.getId()));
            vo.setSatoken(StpUtil.getTokenValue());
            LoginUserInfoVo o = (LoginUserInfoVo) StpUtil.getSession().get(CommonConstant.SESSION_USER_KEY);
            if (o == null){
                return HttpResponseEntity.error(401, "未获取到用户登录信息！");
            }
            o.setDepartmentName(list2.get(0).getDepartmentName());
            o.setUnitName(list2.get(0).getUnitName());
            if (o.isFirst()) {
                vo.setFirst(true);
            }else {
                vo.setFirst(false);
            }
            List<Integer> list =new ArrayList<>();
            list.add(Math.toIntExact(sysLoginUser.getId()));
            Map<String,Object> map = sysMenuService.getMenuByUserIds(list);
            List<String> permissionList = new ArrayList<>();
            List<String> permissionRoleList = new ArrayList<>();
            String permissions = "";
            String permissionsRole = "";
                //权限数组
                List<String> sysMenuList = (List<String> )map.get("sysMenuList");
                for (int i = 0 ; i < sysMenuList.size() ; i++){
                    if (i == sysMenuList.size()-1){
                        permissions += sysMenuList.get(i);
                        permissionList.add(sysMenuList.get(i));
                    }else {
                        permissions += sysMenuList.get(i)+",";
                        permissionList.add(sysMenuList.get(i));
                    }
                }
                //权限角色数组
                List<String> sysMenuRoleList = (List<String> )map.get("sysMenuRoleList");
                for (int i = 0 ; i < sysMenuRoleList.size() ; i++){
                    if (i == sysMenuRoleList.size()-1){
                        permissionsRole += sysMenuRoleList.get(i);
                        permissionRoleList.add(sysMenuRoleList.get(i));
                    }else {
                        permissionsRole += sysMenuRoleList.get(i)+",";
                        permissionRoleList.add(sysMenuRoleList.get(i));
                    }
                }
            vo.setPermissionList(permissionList);
            vo.setPermissionRoleList(permissionRoleList);
            o.setPermissionRoleList(permissionRoleList);
            o.setPermissionList(permissionList);
            StpUtil.getSession().set(CommonConstant.SESSION_USER_KEY, o);

            return HttpResponseEntity.success(vo);
        } catch (Exception e) {
            log.error(e.getMessage());
            return HttpResponseEntity.error(500, e.toString());
        }
    }


    /**
     * 用户注销
     *
     * @return String
     * @author tqx
     * @date 2024/11/27 15:15
     */
    @GetMapping(value = "/logout")
    public HttpResponseEntity logout() {
        try {
            List<TokenSign> tokenSignList = StpUtil.getSession().getTokenSignList();

            if (isConcurrent && tokenSignList.size() > 1){
                //允许并发登录
                String tokenValue = StpUtil.getTokenValue();
                StpUtil.logoutByTokenValue(tokenValue);
            }else{
                StpUtil.getSession().logout();
                StpUtil.logout();
            }

            return HttpResponseEntity.success("注销成功");
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.toString());
        }
    }


    /**
     * 更改密码
     * @author tqx
     * @date 2024/11/27 17:30
     * Description: 更改密码
     * @param req
     * @return HttpResponseEntity
     */
    @PostMapping("/modifyPassword")
    public HttpResponseEntity modifyPassword(@Valid @RequestBody UserPasswordReq req) {
        try {
            Integer id= StpUtil.getLoginIdAsInt();
//            if(!req.getPassword().equals(req.getConfirmPassword())) {
//                return HttpResponseEntity.error(500,"两次输入密码不一致,请重新输入");
//            }
            TBackLoginUser sysLoginUser =  tBackLoginUserService.getById(id);
            if (sysLoginUser==null){
                return HttpResponseEntity.error(500,"查询不到当前用户的信息！请检查数据！");
            }else if (sysLoginUser.getState().compareTo(CommonConstant.StateActive.Deleted)==0) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
            boolean equals = SM4.encryptECB(req.getOlderPassword(), secretKey).equals(sysLoginUser.getPassword());
            if (!equals){
                return HttpResponseEntity.error(500, "原始密码错误");
            }
            sysLoginUser.setPassword(SM4.encryptECB(req.getPassword(), secretKey));
            if (ObjectUtils.isEmpty(sysLoginUser.getLastLoginTime())){
                //是第一次登陆修改密码
                sysLoginUser.setLastLoginTime(new Date());
                LoginUserInfoVo o = (LoginUserInfoVo) StpUtil.getSession().get(CommonConstant.SESSION_USER_KEY);
                o.setFirst(false);
                StpUtil.getSession().set(CommonConstant.SESSION_USER_KEY, o);
            }
            tBackLoginUserService.saveOrUpdate(sysLoginUser);
            return HttpResponseEntity.success("修改密码成功！");
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }

    /**
     * 获取后台系统所有账号信息查询
     * @author tqx
     * @date 2024/11/27 17:30
     * Description: 获取后台系统所有账号信息查询
     * @param page
     * @return HttpResponseEntity
     */
    @PostMapping("/getAllUserInfo")
    public HttpResponseEntity getAllUserInfo(@RequestBody PageRequestEntity page) {
        try{
            Integer userId = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(userId);
            if (tBackLoginUser==null){
                return HttpResponseEntity.error(500,"查询不到该用户的信息！请检查数据！");
            }else if (tBackLoginUser.getState().compareTo(CommonConstant.StateActive.Deleted)==0) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
//            if (tBackLoginUser.getIsAdmin().compareTo(CommonConstant.BackIsAdmin.Yes)!=0){
//                return HttpResponseEntity.error(500,"该用户不是超级管理员，无法查询用户列表！");
//            }

            TBackLoginUserReq req = new TBackLoginUserReq();
            req.setCurrent(page.getCurrentPage());
            req.setSize(page.getPageSize());
            if (!ObjectUtils.isEmpty(page.getQuery().get("userName"))){
                req.setUserName(page.getQuery().get("userName").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("name"))){
                req.setName(page.getQuery().get("name").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("unitId"))){
                List<String> list = Arrays.asList(page.getQuery().get("unitId").toString().split(","));
                req.setUnitIds(EntityUtils.strToInt(list));
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("phone"))){
                req.setPhone(page.getQuery().get("phone").toString());
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("state"))){
                req.setState(Integer.valueOf(page.getQuery().get("state").toString()));
            }
            if (!ObjectUtils.isEmpty(page.getQuery().get("isAdmin"))){
                req.setIsAdmin(Integer.valueOf(page.getQuery().get("isAdmin").toString()));
            }
            if (!ObjectUtils.isEmpty(page.getSort()) && page.getSort().get(0).getType()!=null){
                req.setOrders(EntityUtils.sort(page));
            }
            Page<TBackLoginUserVo> page1 = tBackLoginUserMapper.pageQuery(req);
            PageEntity entity = PageEntityBuilder.builder()
                    .data(page1.getRecords())
                    .currentPage(page1.getCurrent())
                    .pageSize(page1.getSize())
                    .totalCount(page1.getTotal())
                    .totalPage(page1.getPages())
                    .build();
            return HttpResponseEntity.success(entity);
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }

    /**
     * 新增/修改后台系统账号信息
     * @author tqx
     * @date 2024/11/27 17:30
     * Description: 新增/修改后台系统所有账号信息查询
     * @param tBackLoginUserComm
     * @return HttpResponseEntity
     */
    @Transactional
    @PostMapping("/saveOrUpdateUserInfo")
    public HttpResponseEntity saveOrUpdateUserInfo(@RequestBody TBackLoginUser tBackLoginUserComm) {
        try{
            Integer userId = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(userId);
            if (tBackLoginUser==null){
                return HttpResponseEntity.error(500,"查询不到该用户的信息！请检查数据！");
            }else if (tBackLoginUser.getState().compareTo(CommonConstant.StateActive.Deleted)==0) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
            if (tBackLoginUser.getIsAdmin().compareTo(CommonConstant.BackIsAdmin.Yes)!=0){
                return HttpResponseEntity.error(401,"该用户不是超级管理员，无法做新增或者修改操作!");
            }
            //查询账号是否存在
            Map<String, Object> params = new HashMap<>();
            params.put("userName",tBackLoginUserComm.getUserName());
            List<TBackLoginUser> list = tBackLoginUserMapper.findAllByMap(params);
            if (list.size()>0){
                if (tBackLoginUserComm.getId()==null){
                    return HttpResponseEntity.error(500,"该用户名已存在有效账号，请重新输入！");
                }else {
                    if (!list.get(0).getId().equals(tBackLoginUserComm.getId())){
                        return HttpResponseEntity.error(500,"该用户名已存在有效账号，请重新输入！");
                    }
                }
            }
            if (tBackLoginUserComm.getId()!=null){
                //是修改账号
                tBackLoginUserService.saveOrUpdate(tBackLoginUserComm);
                //后台用户是修改  则角色和数据权限 是最新的权限集合
                sysUserRoleService.remove(new QueryWrapper<SysUserRole>().eq("user_id",tBackLoginUserComm.getId()));
                if (!ObjectUtils.isEmpty(tBackLoginUserComm.getSysUserRoles())){
                    sysUserRoleService.saveOrUpdateBatch(tBackLoginUserComm.getSysUserRoles());
                }
                //强制登出该账号
                List<TBackLoginUser> loginUserList = new ArrayList<>();
                loginUserList.add(tBackLoginUserComm);
//                tBackLoginUserService.userLogOut(loginUserList);
                // 发布事件
                eventPublisher.publishEvent(new BatchLogoutEvent(
                        loginUserList.stream()
                                .map(TBackLoginUser::getId)
                                .collect(Collectors.toList())
                ));
            }else {
                //新增 设置初始密码
                tBackLoginUserComm.setPassword(SM4.encryptECB(firstPw, secretKey));
                tBackLoginUserService.saveOrUpdate(tBackLoginUserComm);

                //后台用户是新增  则角色和数据权限 必然是新增
                if (!ObjectUtils.isEmpty(tBackLoginUserComm.getSysUserRoles())){
                    for (SysUserRole sysUserRole : tBackLoginUserComm.getSysUserRoles()) {
                        sysUserRole.setUserId(tBackLoginUserComm.getId());
                    }
                    sysUserRoleService.saveOrUpdateBatch(tBackLoginUserComm.getSysUserRoles());
                }
            }
            return HttpResponseEntity.success("操作成功！");
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }

    /**
     * 根据后台用户的ID查询对应的角色和数据权限
     *
     * @param userId
     * @return HttpResponseEntity
     * @author tqx
     * @date 2025/4/27 15:30
     * Description: 根据后台用户的ID查询对应的角色和数据权限
     */
    @GetMapping("/queryRoleDataByUserId/{userId}")
    public HttpResponseEntity queryRoleDataByUserId(@PathVariable("userId") Integer userId) {
        try {
            Map<String, Object> params = new HashMap<>();
            params.put("userId", userId);
            List<RoleDataVo> voList = sysUserRoleMapper.queryRoleDataByUserId(params);
            List<RoleDataVo> newList = new ArrayList<>();
            //根据unit_sort进行分组
            Map<Integer, List<RoleDataVo>> map = voList.stream().collect(Collectors.groupingBy(RoleDataVo::getUnitSort));
            map = map.entrySet().stream().sorted(Map.Entry.comparingByKey()).collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, (e1, e2) -> e2, LinkedHashMap::new));
            for (Map.Entry<Integer, List<RoleDataVo>> entry : map.entrySet()) {
                List<RoleDataVo> roleDataVoList = entry.getValue();
                //根据数据权限dataSort排序
                roleDataVoList.sort(Comparator.comparing(RoleDataVo::getDataSort));
                newList.addAll(roleDataVoList);
            }
            return HttpResponseEntity.success(newList);
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.toString());
        }
    }


    /**
     * 删除后台账号-管理员能操作
     * @author tqx
     * @date 2024/11/27 17:30
     * Description: 删除后台账号-管理员能操作
     * @param id
     * @return HttpResponseEntity
     */
    @DeleteMapping("/deleteUserInfo/{id}")
    @Transactional
    public HttpResponseEntity deleteUserInfo(@PathVariable("id") String id) {
        try{
            Integer userId = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(userId);
            if (tBackLoginUser==null){
                return HttpResponseEntity.error(500,"查询不到当前用户的信息！请检查数据！");
            }else if (tBackLoginUser.getState().compareTo(CommonConstant.StateActive.Deleted)==0) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
//            if (tBackLoginUser.getIsAdmin().compareTo(CommonConstant.BackIsAdmin.Yes)!=0)
//                return HttpResponseEntity.error(500,"当前用户不是超级管理员，无法做删除");

            List<String> list = Arrays.asList(id.split(","));
            List<Integer> list1 = new ArrayList<>();
            for (String s : list) {
                list1.add(Integer.parseInt(s));
            }
            Map<String, Object> params = new HashMap<>();
            params.put("ids", list1);
            params.put("state", CommonConstant.StateActive.Active);
            List<TBackLoginUser> tBackLoginUsers = tBackLoginUserMapper.findAllByMap(params);
            if (ObjectUtils.isEmpty(tBackLoginUsers)){
                return HttpResponseEntity.error(500,"查询不到选择的用户的信息！请检查数据！");
            }
            for (TBackLoginUser tBackLoginUser1 : tBackLoginUsers) {
                if (tBackLoginUser1.getState().compareTo(CommonConstant.StateActive.Deleted)==0){
                    return HttpResponseEntity.error(500,"选择的用户中存在已被删除的用户！请检查数据！");
                }else {
                    tBackLoginUser1.setState(CommonConstant.StateActive.Deleted);
                }
            }
            if(tBackLoginUserService.saveOrUpdateBatch(tBackLoginUsers)){
                //把tBackLoginUsers的用户Id抽离出来
//                tBackLoginUserService.userLogOut(tBackLoginUsers);
                // 发布事件
                eventPublisher.publishEvent(new BatchLogoutEvent(
                        tBackLoginUsers.stream()
                                .map(TBackLoginUser::getId)
                                .collect(Collectors.toList())
                ));
            }
         return HttpResponseEntity.success("操作成功！");
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }

    /**
     * 重置密码-管理员能操作
     * @author tqx
     * @date 2024/11/27 17:30
     * Description: 重置密码-管理员能操作
     * @param id
     * @return HttpResponseEntity
     */
    @GetMapping("/resetPassword/{id}")
    public HttpResponseEntity resetPassword(@PathVariable("id") Integer id) {
        try{
            Integer userId = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(userId);
            if (tBackLoginUser==null){
                return HttpResponseEntity.error(500,"查询不到当前用户的信息！请检查数据！");
            }else if (tBackLoginUser.getState().compareTo(CommonConstant.StateActive.Deleted)==0) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
//            if (tBackLoginUser.getIsAdmin().compareTo(CommonConstant.BackIsAdmin.Yes)!=0)
//                return HttpResponseEntity.error(500,"当前用户不是超级管理员，无法做删除");
            TBackLoginUser tBackLoginUser2 = tBackLoginUserService.getById(id);
            if (ObjectUtils.isEmpty(tBackLoginUser2)){
                return HttpResponseEntity.error(500,"查询不到选择的用户的信息！请检查数据！");
            }
            tBackLoginUser2.setPassword(SM4.encryptECB(firstPw, secretKey));
            tBackLoginUser2.setLastLoginTime(null);
            tBackLoginUserMapper.updatePhone(tBackLoginUser2.getId(),null,tBackLoginUser2.getPassword());
            return HttpResponseEntity.success("操作成功！");
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }

    /**
     * 管理员能操作-后台系统账户生效激活
     * @author tqx
     * @date 2024/11/27 17:30
     * Description: 管理员能操作-后台系统账户生效激活
     * @param id
     * @return HttpResponseEntity
     */
    @GetMapping("/active/{id}")
    public HttpResponseEntity active(@PathVariable("id") Integer id) {
        try{
            Integer userId = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(userId);
            if (tBackLoginUser==null){
                return HttpResponseEntity.error(500,"查询不到当前用户的信息！请检查数据！");
            }else if (tBackLoginUser.getState().compareTo(CommonConstant.StateActive.Deleted)==0) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
            if (tBackLoginUser.getIsAdmin().compareTo(CommonConstant.BackIsAdmin.Yes)!=0)
                return HttpResponseEntity.error(500,"当前用户不是超级管理员，无法激活该账号");
            TBackLoginUser tBackLoginUser2 = tBackLoginUserService.getById(id);
            if (ObjectUtils.isEmpty(tBackLoginUser2)){
                return HttpResponseEntity.error(500,"查询不到选择的用户的信息！请检查数据！");
            }
            //查询有效账户名是否存在
//            Map<String, Object> params = new HashMap<>();
//            params.put("userName",tBackLoginUser2.getUserName());
//            List<TBackLoginUser> list = tBackLoginUserMapper.findAllByMap(params);
//            if (list.size()>0){
//                return HttpResponseEntity.error(500,"该用户名已存在有效的账号，无法激活该账号！");
//            }
            tBackLoginUser2.setState(CommonConstant.StateActive.Active);
            tBackLoginUserService.saveOrUpdate(tBackLoginUser2);
            return HttpResponseEntity.success("操作成功！");
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }

    /**
     * 根据用户的id查询该用户多个角色的菜单权限
     * @author tqx
     * @date 2025/4/28 16:52
     * @company DFLC
     * Description:
     * @param userId
     * @return HttpResponseEntity
     */
    @GetMapping("/getMenuList/{userId}")
    public HttpResponseEntity getMenuList(@PathVariable("userId") Integer userId) {
        try {
            Integer userId2 = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(userId2);
            if (tBackLoginUser==null){
                return HttpResponseEntity.error(500,"查询不到当前用户的信息！请检查数据！");
            }else if (tBackLoginUser.getState().compareTo(CommonConstant.StateActive.Deleted)==0) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
            if (tBackLoginUser.getIsAdmin().intValue()==CommonConstant.BackIsAdmin.Yes){
                //是超级管理员则查询全部后台的菜单树
                List<SysMenu> entity = sysMenuService.getMenuByUserIds3();
                return HttpResponseEntity.success(entity);
            }else {
                List<Integer> integerList = new ArrayList<>();
                integerList.add(userId);
                List<SysMenu> entity = sysMenuService.getMenuByUserIds2(integerList);
                return HttpResponseEntity.success(entity);
            }
        } catch (Exception e) {
            return HttpResponseEntity.error(500, e.toString());
        }
    }


    /**
     * 获取后台系统所有账号
     * @author tqx
     * @date 2025/7/16 17:30
     * Description: 获取后台系统所有账号
     * @return HttpResponseEntity
     */
    @GetMapping("/getAllUser")
    public HttpResponseEntity getAllUser() {
        try{
            Integer userId = StpUtil.getLoginIdAsInt();
            TBackLoginUser tBackLoginUser = tBackLoginUserService.getById(userId);
            if (tBackLoginUser==null){
                return HttpResponseEntity.error(500,"查询不到该用户的信息！请检查数据！");
            }else if (tBackLoginUser.getState().compareTo(CommonConstant.StateActive.Deleted)==0) {
                return HttpResponseEntity.error(401, "当前用户已被删除！");
            }
            Map<String, Object> params5 = new HashMap<>();
            params5.put("state",CommonConstant.StateActive.Active);
            List<TBackLoginUserVo> list = tBackLoginUserMapper.findAllByMap2(params5);
            List<TBackLoginUserVo2> list1 = new ArrayList<>();
            for (TBackLoginUserVo vo : list) {
                TBackLoginUserVo2 tBackLoginUserVo2 = new TBackLoginUserVo2();
                BeanUtils.copyProperties(vo,tBackLoginUserVo2);
                list1.add(tBackLoginUserVo2);
            }
            return HttpResponseEntity.success(list1);
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }




    /**
     * 根据unitId、角色code获取对应账号
     * @author tqx
     * @date 2025/7/17 14:30
     * Description: 根据unitId、角色code获取对应账号
     * @return HttpResponseEntity
     */
    @PostMapping("/getAllUserByUnitIdAndCode")
    @CheckUser
    public HttpResponseEntity getAllUserByUnitIdAndCode(@RequestBody QueryUserReq req) {
        try{
            Map<String, Object> params5 = new HashMap<>();
            if (!ObjectUtils.isEmpty(req.getDepartmentId())){
                params5.put("departmentId",req.getDepartmentId());
            }
            if (!ObjectUtils.isEmpty(req.getUnitId())){
                params5.put("unitId",req.getUnitId());
            }
            if (!ObjectUtils.isEmpty(req.getRoleCode())){
                //先查询角色的id
                Map<String, Object> params = new HashMap<>();
                params.put("code",req.getRoleCode());
                List<SysRole> list = sysRoleMapper.findAllByMap(params);
                if (ObjectUtils.isEmpty(list) || list.size()!=1){
                    return HttpResponseEntity.error(500,"该角色不存在！");
                }
                //end
                params5.put("roleId",list.get(0).getId());
            }
            List<TBackLoginUserVo> list = tBackLoginUserMapper.findAllByMap3(params5);
            List<TBackLoginUserVo2> list1 = new ArrayList<>();
            for (TBackLoginUserVo vo : list) {
                TBackLoginUserVo2 tBackLoginUserVo2 = new TBackLoginUserVo2();
                BeanUtils.copyProperties(vo,tBackLoginUserVo2);
                list1.add(tBackLoginUserVo2);
            }
            return HttpResponseEntity.success(list1);
        }catch (Exception e){
            return HttpResponseEntity.error(500,e.toString());
        }
    }
}
